package com.liaofan.rocketmq.batch;

import com.liaofan.rocketmq.util.StaticBianLiang;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;

import java.util.ArrayList;
import java.util.List;

public class BeatchProducer {
    public static void main(String[] args) throws MQClientException {
        DefaultMQProducer producer = new DefaultMQProducer("mq");
        producer.setNamesrvAddr(StaticBianLiang.NameServerAddress);
        //指定发送消息的最大大小,默认4M
        //仅修改该属性是不行的,还需要修改broker加载的配置文件
        producer.setMaxMessageSize(4 * 1024 * 1024);
        producer.start();

        List<Message> messagesList = new ArrayList<>();

        for (int i = 0; i < 100; i++) {
            byte[] body = ("Hi," + i).getBytes();
            Message message = new Message("topic_beatchProduer", "topic_tag", body);
            messagesList.add(message);
        }

        //定义消息列表分割器，将消息列表分割为多个不超出4M大小的小列表
        MessageListSplitter messageListSplitter = new MessageListSplitter(messagesList);

        while (messageListSplitter.hasNext()) {
            try {
                List<Message>
                        listItem = messageListSplitter.next();
                producer.send(listItem);
                //producer.send(listItem);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
